package com.aly.beanValidate.core.validator.impl;

import com.aly.beanValidate.core.FieldDefinition;
import com.aly.beanValidate.core.GlobalConfigs;
import com.aly.beanValidate.core.Util;
import com.aly.beanValidate.core.validator.CheckValidator;
import com.aly.beanValidate.core.validator.Name;
import com.aly.beanValidate.i.BeanInfo;
import com.aly.beanValidate.i.FileInfo;
import com.aly.beanValidate.i.FileInfos;
import org.dom4j.Element;

import java.util.Set;

@Name("Ref")
public class RefValidate extends CheckValidator {
    private final String refModel;

    public RefValidate(Element element, GlobalConfigs globalConfigs) {
        super(element, globalConfigs);
        refModel = Util.attr(element, "model");
    }

    @Override
    public StringBuffer doValidate(FieldDefinition field, Object val, BeanInfo bean, FileInfo fileInfo, FileInfos fileInfos) {
        Set<String> alias = globalConfigs.getAlias(refModel);
        if (null == alias || alias.size() == 0) {
            if (!haveConfig(val, fileInfos, refModel)) {
                return new StringBuffer("参照表:[").append(refModel).append("] ID:[").append(val).append("]不存在");
            }
            return null;
        } else {
            for (String ali : alias) {
                if (haveConfig(val, fileInfos, ali)) {
                    return null;
                }
            }
            return new StringBuffer("参照表:[").append(refModel).append("]" + "Alias:").append(alias).append(" ID:[").append(val).append("]不存在");
        }
    }

    private boolean haveConfig(Object val, FileInfos fileInfos, String name) {
        FileInfo fileByName = fileInfos.getFileByName(name);
        return null != fileByName && null != fileByName.getBeanByID(String.valueOf(val));
    }
}
